
import { createTextVNode, createEmptyVNode } from '../../vdom/vnode'
import { isObject, noop } from '../../../util/index'
import { resolveAsset } from '../../util/options'




function toString(val) {
    return val == null
        ? ''
        : Array.isArray(val) || (typeof val === 'object')
            ? JSON.stringify(val, null, 2)
            : String(val)
}

function renderList(val, render) {
    let ret, i, l, keys, key
    if (Array.isArray(val) || typeof val === 'string') {
        ret = new Array(val.length)
        for (i = 0, l = val.length; i < l; i++) {
            ret[i] = render(val[i], i)
        }
    } else if (typeof val === 'number') {
        ret = new Array(val)
        for (i = 0; i < val; i++) {
            ret[i] = render(i + 1, i)
        }
    } else if (isObject(val)) {
        keys = Object.keys(val)
        ret = new Array(keys.length)
        for (i = 0, l = keys.length; i < l; i++) {
            key = keys[i]
            ret[i] = render(val[key], key, i)
        }
    }
    return ret
}

function resolveFilter(id) {
    id = id.trim()
    return resolveAsset(this.$options, 'filters', id, true)
}

function renderSlot(
    name,
    props
) {
    const scopedSlotFn = this.$scopedSlots[name] || noop
    if(name === 'default'){
        return scopedSlotFn
    }else{
        return scopedSlotFn.call(this,props)
    }
}


//普通插槽内容,单纯包装一下
export function resolveSlots (
  children
) {
  if (!children || !children.length) {
    return {}
  }
  const slots = {}
  for (let i = 0, l = children.length; i < l; i++) {
    const child = children[i];
    (slots.default || (slots.default = [])).push(child)
  }
  return slots
}
//命名插槽内容，封装起来
function resolveScopedSlots (
    fns,
    res
  ) {
    res = res || { }
    for (let i = 0; i < fns.length; i++) {
      const slot = fns[i]
      if (Array.isArray(slot)) {
        resolveScopedSlots(slot, res)
      } else if (slot) {
        res[slot.key] = slot.fn
      }
    }
    return res
  }
export function installRenderHelpers(target) {
    target._s = toString //将内容转字符串
    target._t = renderSlot //插槽
    target._f = resolveFilter //过滤器
    target._l = renderList //渲染数组列表
    target._v = createTextVNode //文本vNode
    target._e = createEmptyVNode //空vnode
    target._u = resolveScopedSlots
}